<template>
    <div class="app-container">
        <el-row :gutter="20">
            <!--科室数据-->
            <el-col :span="3" :xs="20" style="width: 11%;border-right-style: solid;border-width: 1px">
                <div class="head-container">
                    <el-input v-model="deptName" placeholder="请输入科室账号" clearable size="small" prefix-icon="el-icon-search" style="margin-bottom: 20px"/>
                </div>
                <div class="head-container">
                    <el-tree :data="deptOptions" :props="defaultProps" :expand-on-click-node="false" :filter-node-method="filterNode" ref="tree" node-key="id" default-expand-all highlight-current @node-click="handleNodeClick"/>
                </div>
            </el-col>
            <!--人脸数据-->
            <el-col :span="20" :xs="24" style="width: 89%">
                <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
                    <el-form-item label="用户">
                        <el-input v-model="queryParams.nickName" placeholder="请输入用户名" clearable size="mini"/>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索
                        </el-button>
                        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
                    </el-form-item>
                </el-form>

                <el-row :gutter="10" class="mb8">
<!--                    <el-col :span="1.5">-->
<!--                        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"-->
<!--                                   v-hasPermi="['face:face_list:add']">新增-->
<!--                        </el-button>-->
<!--                    </el-col>-->
                    <el-col :span="1.5">
                        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single"
                                   @click="handleUpdate"
                                   v-hasPermi="['face:face_list:edit']">修改
                        </el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple"
                                   @click="handleDelete" v-hasPermi="['face:face_list:remove']">删除
                        </el-button>
                    </el-col>
<!--                    <el-col :span="1.5">-->
<!--                        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"-->
<!--                                   v-hasPermi="['face:face_list:export']">导出-->
<!--                        </el-button>-->
<!--                    </el-col>-->
                    <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
                </el-row>

                <el-table v-loading="loading" :data="face_listList" @selection-change="handleSelectionChange" :height="table_height">
                    <el-table-column type="selection" width="55" align="center"/>
                    <el-table-column label="用户" align="center" prop="nickName"/>
                    <el-table-column label="创建时间" align="center" prop="updateTime" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="最近修改时间" align="center" prop="updateTime" width="180">
                        <template slot-scope="scope">
                            <span>{{ parseTime(scope.row.updateTime, '{y}-{m}-{d}') }}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                                       v-hasPermi="['face:face_list:edit']">修改
                            </el-button>
                            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                                       v-hasPermi="['face:face_list:remove']">删除
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum"
                            :limit.sync="queryParams.pageSize" @pagination="getList"/>
            </el-col>
        </el-row>


        <!-- 添加或修改人脸数据对话框 -->
        <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <!-- 居中显示 -->
                <div style="width: 100%; max-width: 800px;margin-left: -20px">
                    <!-- 上传和图片对比区域 -->
                    <div style="padding-left: 50px;">
                        <!-- 上传组件 - 居中显示 -->
                        <div style="width: 100%; text-align: center; margin-bottom: 20px;">
                            <el-upload
                                ref="upload"
                                :limit="1"
                                accept=".png,.jpg,.jpeg"
                                action="#"
                                drag
                                :on-change="pictureChange"
                                :before-remove="pictureRemove"
                                :auto-upload="false"
                                :disabled="uploading">
                                <div v-if="uploading" style="text-align: center;">
                                    <i class="el-icon-loading" style="font-size: 48px; color: #409EFF;"></i>
                                </div>
                                <div v-else>
                                    <i class="el-icon-upload"></i>
                                    <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
                                </div>
                                <div class="el-upload__tip text-center" slot="tip">
                                    <span>图片中人脸尺寸建议600*600; 最小不小于80*80像素; 图片大小小于10MB; 图像清晰！</span>
                                </div>
                            </el-upload>
                        </div>

                        <!-- 图片展示对比区域 -->
                        <div v-if="hasImages" style="width: 100%; margin-top: 20px;">
                            <!-- 单选按钮组 - 居中显示 -->
                            <div v-if="originalImageUrl && newImageUrl" style="text-align: center; margin-bottom: 15px;">
                                <el-radio-group v-model="selectedImageType" @change="handleImageSelection">
                                    <el-radio-button
                                        label="original"
                                        size="medium">
                                        原图
                                    </el-radio-button>
                                    <el-radio-button
                                        label="new"
                                        size="medium">
                                        新图
                                    </el-radio-button>
                                </el-radio-group>
                            </div>

                            <!-- 图片对比展示 -->
                            <div style="display: flex; justify-content: center; gap: 30px; flex-wrap: wrap;">
                                <!-- 原始图片展示 -->
                                <div v-if="originalImageUrl" style="position: relative; text-align: center;">
                                    <div style="font-size: 14px; margin-bottom: 5px; color: #409EFF;">原图</div>
                                    <div style="position: relative; display: inline-block;">
                                        <img
                                            :src="originalImageUrl"
                                            style="width: 178px; height: 178px; display: block; margin: 0 auto; border: 1px solid #ddd; border-radius: 5px;">
                                        <el-button
                                            type="danger"
                                            icon="el-icon-delete"
                                            size="mini"
                                            style="position: absolute; top: -10px; right: -10px; padding: 5px; border-radius: 50%;"
                                            @click="removeOriginalImage"
                                            title="删除原图">
                                        </el-button>
                                    </div>
                                </div>

                                <!-- 新上传图片展示 -->
                                <div v-if="newImageUrl" style="position: relative; text-align: center;">
                                    <div style="font-size: 14px; margin-bottom: 5px; color: #67C23A;">新图</div>
                                    <div style="position: relative; display: inline-block;">
                                        <img
                                            :src="newImageUrl"
                                            style="width: 178px; height: 178px; display: block; margin: 0 auto; border: 1px solid #ddd; border-radius: 5px;">
                                        <el-button
                                            type="danger"
                                            icon="el-icon-delete"
                                            size="mini"
                                            style="position: absolute; top: -10px; right: -10px; padding: 5px; border-radius: 50%;"
                                            @click="removeNewImage"
                                            title="删除新上传图片">
                                        </el-button>
                                    </div>
                                </div>
                            </div>

                            <!-- 选中图片信息显示 -->
                            <div v-if="selectedImageType" style="text-align: center; margin-top: 15px; padding: 10px; background-color: #f5f7fa; border-radius: 5px;">
                                <span style="font-weight: bold;">
                                    选中：{{ selectedImageType === 'original' ? '原图' : '新图' }}
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm" :disabled="!newImageUrl && !originalImageUrl">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import {listFace_list, delFace_list, addFace_list_url, updateFace_list_url} from "@/api/face/face_list";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {deptTreeSelect, listUser} from "@/api/system/user";
import {isEmpty, isEmptyStr} from "@/utils/zzDouUtils/objUtil";
import {nowDateStr} from "@/utils/zzDouUtils/dateUtil";
import {uploadToMinIO} from "@/api/common/minio";

export default {
    name: "Face_list",
    components: {Treeselect},
    data() {
        return {
            // 科室账号
            deptName: undefined,
            // 科室树选项
            deptOptions: undefined,
            defaultProps: {
                children: "children",
                label: "label"
            },
            // 遮罩层
            loading: true,
            uploading: false, // MinIO上传状态
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 人脸数据表格数据
            face_listList: [],
            // 弹出层标题
            title: "",
            // 是否显示弹出层
            open: false,
            // 人脸特征值时间范围
            daterangeUpdateTime: [],
            // 人脸特征值时间范围
            daterangeCreateTime: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                params: {},
            },
            isAdd: true,
            // 表单参数
            form: {
                id: null,
                imageUrl: null,
            },
            form_file: null,
            imageFrom: null,
            // 图片对比相关数据
            originalImageUrl: null, // 原始图片URL（编辑模式下）
            newImageUrl: null,      // 新上传的图片URL
            selectedImageType: '',  // 选中的图片类型：'original' | 'new'
            // 表单校验
            rules: {
                id: [
                    { required: true, message: '请选择用户', trigger: 'change' }
                ]
            },
            //用户列表
            userList: [],
            // 表格高度
            table_height: undefined,
        };
    },
    computed: {
        hasImages() {
            return this.originalImageUrl || this.newImageUrl;
        }
    },
    watch: {
        'form.deptId'(n, o) {
            this.deptChange(n);
        },
    },
    created() {
        this.getList();
        this.getDeptTree();
        this.getUserList(null);
    },
    methods: {
        /** 查询科室下拉树结构 */
        getDeptTree() {
            deptTreeSelect().then(response => {
                this.deptOptions = response.data;
            });
        },
        /** 查询人脸数据列表 */
        getList() {
            this.loading = true;
            if (null != this.daterangeUpdateTime && '' != this.daterangeUpdateTime) {
                this.queryParams.params["beginUpdateTime"] = this.daterangeUpdateTime[0];
                this.queryParams.params["endUpdateTime"] = this.daterangeUpdateTime[1];
            }
            if (null != this.daterangeCreateTime && '' != this.daterangeCreateTime) {
                this.queryParams.params["beginCreateTime"] = this.daterangeCreateTime[0];
                this.queryParams.params["endCreateTime"] = this.daterangeCreateTime[1];
            }
            listFace_list(this.queryParams).then(response => {
                this.face_listList = response.rows;
                this.total = response.total;
                this.loading = false;
            });
        },
        // 取消按钮
        cancel() {
            this.open = false;
            this.reset();
        },
        // 表单重置
        reset() {
            this.form = {
                id: null,
                faceFeature: null,
                reservedOne: null,
                reservedTwo: null,
                updateTime: null,
                createTime: null,
                imageUrl: null,
            };
            this.form_file = null;
            // 重置图片对比相关数据
            this.originalImageUrl = null;
            this.newImageUrl = null;
            this.selectedImageType = '';
            this.resetForm("form");
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.daterangeUpdateTime = [];
            this.daterangeCreateTime = [];
            this.queryParams.params.deptId = undefined; // 清理组织ID参数
            this.queryParams.nickName = undefined; // 清理用户名参数
            this.resetForm("queryForm");
            this.handleQuery();
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map(item => item.userId)
            this.single = selection.length !== 1
            this.multiple = !selection.length
        },
        /** 新增按钮操作 */
        handleAdd() {
            this.reset();
            this.open = true;
            this.title = "添加人脸数据";
            this.isAdd = true;
            // 重置图片对比数据
            this.originalImageUrl = null;
            this.newImageUrl = null;
            this.selectedImageType = '';
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            // 如果传入了row对象，直接使用
            if (row && row.userId) {
                this.updateByRow(row);
                return;
            }

            // 如果没有传入row对象，从选中的数据中获取
            if (this.ids.length > 0) {
                const selectedUserId = this.ids[0];
                const selectedRow = this.face_listList.find(item => item.userId === selectedUserId);

                if (selectedRow) {
                    this.updateByRow(selectedRow);
                    return;
                }
            }
            // 如果都没有找到有效数据，提示错误
            this.$modal.msgWarning("未找到要修改的数据，请选择一个用户");
        },

        /**
         * 根据传入的row对象更新表单
         * @param {Object} row 表格行数据
         */
        updateByRow(row) {
            this.reset();

            // 设置原始图片和新图片state
            this.originalImageUrl = row.imageUrl; // 设置原始图片
            this.newImageUrl = null; // 清空新图片

            // 🔧 重要修复：正确设置form.imageUrl
            this.form.imageUrl = row.imageUrl; // 重要：确保回显时form.imageUrl有值

            // 默认选中原始图片
            this.selectedImageType = 'original';
            this.form.minioUrl = row.minioUrl;
            this.form.id = row.userId;
            this.isAdd = false;
            this.open = true;
            this.title = "修改人脸数据";
        },

        //文件改变事件 - 直接上传到MinIO
        pictureChange(file, fileList) {
            // 显示上传中状态
            this.uploading = true;
            // 直接上传到MinIO
            uploadToMinIO(file.raw).then(response => {
                this.uploading = false;
                if (response.code === 200) {
                    // MinIO上传成功，获取返回的图片URL
                    const imageUrl = response.data;
                    if (!imageUrl) {
                        this.$modal.msgError('图片上传成功但未获取到URL，请检查后端MinIO配置');
                        return;
                    }

                    // 设置新上传的图片URL
                    this.newImageUrl = imageUrl;
                    this.form.imageUrl = imageUrl;
                    this.form.minioUrl = imageUrl;

                    // 如果有两张图，默认选择新图
                    if (this.originalImageUrl && this.newImageUrl) {
                        this.selectedImageType = 'new';
                    }
                    // 如果只有新图片，自动选中它
                    else if (!this.originalImageUrl && !this.selectedImageType) {
                        this.selectedImageType = 'new';
                    }

                    // 🔧 关键修复：清空el-upload组件内的文件列表，支持连续上传
                    this.$refs.upload.clearFiles();

                    this.$modal.msgSuccess('图片上传成功');
                } else {
                    throw new Error(response.msg || '上传失败');
                }
            }).catch(error => {
                this.uploading = false;
                // 更详细的错误提示
                let errorMsg = '图片上传失败';
                if (error.message) {
                    errorMsg += ': ' + error.message;
                } else if (error.response && error.response.data) {
                    errorMsg += ': ' + (error.response.data.message || error.response.data.msg || '服务器错误');
                } else {
                    errorMsg += ': 请检查后端MinIO服务是否启动';
                }

                this.$modal.msgError(errorMsg);
                // 清除文件
                this.form_file = null;
                this.form.imageUrl = null;
                this.form.minioUrl = null;
                this.newImageUrl = null; // 清除新图片URL
            });
        },
        pictureRemove(file, fileList) {
            this.form_file = null;
            this.form.imageUrl = null;
            // 清除新上传的图片（不清除原始图片）
            this.newImageUrl = null;
            // 如果删除了新图片且当前选中的是新图片，重新选择
            if (this.selectedImageType === 'new') {
                this.selectedImageType = this.originalImageUrl ? 'original' : '';
            }
        },
        /** 提交按钮 - 仅图片上传模式 */
        submitForm() {
            // 验证用户选择
            if (isEmptyStr(this.form.id)) {
                this.$modal.msgWarning("请选择用户");
                return;
            }

            // 获取要提交的图片URL
            let imageUrlToSubmit = '';

            // 根据选中的图片类型决定提交哪个图片
            if (this.selectedImageType === 'original') {
                imageUrlToSubmit = this.originalImageUrl || this.newImageUrl;
            } else if (this.selectedImageType === 'new') {
                imageUrlToSubmit = this.newImageUrl;
            } else if (this.newImageUrl) {
                // 没有选中类型但有新图片，使用新图片
                imageUrlToSubmit = this.newImageUrl;
                this.selectedImageType = 'new';
            } else if (this.originalImageUrl) {
                // 没有选中类型但有原始图片，使用原始图片
                imageUrlToSubmit = this.originalImageUrl;
                this.selectedImageType = 'original';
            }

            // 确保imageUrlToSubmit不为空
            if (isEmptyStr(imageUrlToSubmit)) {
                this.$modal.msgWarning("请上传要保存的图片");
                return;
            }

            this.$refs["form"].validate(valid => {
                if (valid) {
                    // 使用确定的图片URL进行提交
                    if (this.isAdd) {
                        addFace_list_url(imageUrlToSubmit, this.form.id).then(res => {
                            this.$modal.msgSuccess("新增成功");
                            this.open = false;
                            this.getList();
                        });
                    } else {
                        updateFace_list_url(imageUrlToSubmit, this.form.id).then(res => {
                            this.$modal.msgSuccess("修改成功");
                            this.open = false;
                            this.getList();
                        });
                    }
                }
            });
        },
        /** 删除按钮操作 */
        handleDelete(row) {
            const ids = row.userId || this.ids;
            this.$modal.confirm('是否确认删除编号为"' + ids + '"的人脸数据？').then(function () {
                return delFace_list(ids);
            }).then(() => {
                this.getList();
                this.$modal.msgSuccess("删除成功");
            }).catch(() => {
            });
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download('face/face_list/export', {
                ...this.queryParams
            }, `face_list_${nowDateStr()}.xlsx`)
        },
        // 筛选节点
        filterNode(value, data) {
            if (!value) return true;
            return data.label.indexOf(value) !== -1;
        },
        // 节点单击事件
        handleNodeClick(data) {
            this.queryParams.params.deptId = data.id;
            this.handleQuery();
        },
        // 选择科室事件
        deptChange(e) {
            this.getUserList(e);
        },
        /** 查询用户列表 */
        getUserList(deptId) {
            listUser({deptId: deptId,pageSize:1000,pageNum:1}).then(response => {
                    this.userList = response.rows;
                }
            );
        },

        /** 删除图片（仅前端操作，不影响后端） */
        removeImage() {
            this.form.imageUrl = null;
            // 清理相关代码：只处理imageUrl
            this.form_file = null; // 清除上传文件
        },

        /** 图片选择变化处理 */
        handleImageSelection(value) {
            console.log('选中图片类型:', value);
        },

        /** 删除原始图片 */
        removeOriginalImage() {
            if (this.isAdd) {
                // 新增模式下，原始图片就是当前保存的图片
                this.originalImageUrl = null;
                this.form.imageUrl = null;
                this.form.minioUrl = null;
                // 重新设置选中状态
                if (this.newImageUrl) {
                    this.selectedImageType = 'new';
                } else {
                    this.selectedImageType = '';
                }
            } else {
                // 修改模式下，删除原始图片但不改变选中状态（除非选中的就是原始图片）
                this.originalImageUrl = null;
                if (this.selectedImageType === 'original') {
                    if (this.newImageUrl) {
                        this.selectedImageType = 'new';
                    } else {
                        this.selectedImageType = '';
                    }
                }
            }
            this.$modal.msgSuccess('原始图片已删除');
        },

        /** 删除新上传图片 */
        removeNewImage() {
            this.newImageUrl = null;
            this.form.imageUrl = null;
            this.form.minioUrl = null;
            this.form_file = null;

            // 重新设置选中状态
            if (this.originalImageUrl) {
                this.selectedImageType = 'original';
            } else {
                this.selectedImageType = '';
            }
            this.$modal.msgSuccess('新上传图片已删除');
        }
    }
};
</script>
